package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Stream;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper,Clazz> implements ClazzService {
    @Autowired
    public EmpService empService;
    /**
     * 分页查询
     *
     * @param begin
     * @param end
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<Clazz> findPage(String name,LocalDate begin, LocalDate end, int page, int pageSize) {
        IPage<Clazz> pagination=new Page<>(page,pageSize);
        //进行条件查询修改


        LambdaQueryWrapper<Clazz> queryWapper= Wrappers.<Clazz>lambdaQuery()
                .like(name!=null,Clazz::getName,name)
                .eq(begin!=null,Clazz::getBeginDate,begin)
                .eq(end!=null,Clazz::getEndDate,end);
        queryWapper.orderByDesc(Clazz::getUpdateTime);
        IPage<Clazz> pageResult = this.page(pagination,queryWapper);
        List<Clazz> clazzList = pageResult.getRecords();

        long total = pageResult.getTotal();

        //解决班主任姓名显示问题
        List<Integer> masterList = clazzList.stream().map(clazz -> clazz.getMasterId()).toList();
       masterList = masterList.stream().distinct().toList();
       if(!CollectionUtils.isEmpty(masterList)){
           List<Emp> empList = empService.listByIds(masterList);
          clazzList.forEach(
             clazz -> empList.stream().filter(emp -> emp.getId().equals(clazz.getMasterId()))
                     .findFirst()
                     .ifPresent(emp -> clazz.setMasterName(emp.getName()))
          );

       }
        return new PageResult<>(total,clazzList);
    }

    /**
     * 新增员工
     *
     * @param clazz
     */
    @Override
    public void add(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazz.setCreateTime(LocalDateTime.now());
        this.save(clazz);
    }

    @Override
    public Clazz getByIdClazz(Integer id) {
        Clazz byId = this.getById(id);
        return byId;

    }
}
